
import * as cc from "cc";
import { VMComponentAttr } from "../VMEntity";
import { VMNodeEntity } from './VMNodeEntity';

declare let CC_DEV;
declare let CC_EDITOR;

/**
 * Predefined variables
 * Name = VMComponentEntity
 * DateTime = Sat Mar 19 2022 20:09:15 GMT+0800 (中国标准时间)
 * Author = 272493431
 * FileBasename = VMComponentEntity.ts
 * FileBasenameNoExtension = VMComponentEntity
 * URL = db://assets/scripts/framework/vm/entities/VMComponentEntity.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
 export class VMComponentEntity extends VMNodeEntity{
    execComponents: cc.Component [] = [];
    // @ts-ignore
    observerAttr: VMComponentAttr;
    protected _onChildrenChanged(){
        super._onChildrenChanged();
        if(this.observerAttr.controlChildren){
            this.execComponents.length = 0;
            if(this.node.children.length == 0){
                CC_DEV && console.warn(`VMFactory->VMComponentEntity [${this.node.name}] VMComponentEntity [controlChildren] ,but childrenCount == 0 !!`);                    
            }
            this.node.children.forEach((child)=>{
                // @ts-ignore
                let comp = child.getComponent(this.observerAttr.execComponent);
                // 这里不做非空判断，默认节点有所需 组件
                this.execComponents.push(comp);

                if(comp){
                  
                }else{
                    if(CC_DEV) {
                        console.warn(`VMFactory->VMComponentEntity [${child.name}] 不存在组件 ${cc.js.getClassName(this.observerAttr.execComponent)}`)
                    };   
                }
            });
            
        }
    }
    onValueInit() {
        if(CC_EDITOR){ return; }
        
        if(this.watchNodes.length == 0){
            if(this.observerAttr.controlChildren){
                this._onChildrenChanged();             
            }else{
                this.watchNodes.push(this.node);
                // @ts-ignore
                let comp = this.node.getComponent(this.observerAttr.execComponent);
                // 这里不做非空判断，默认节点有所需 组件
                this.execComponents.push(comp);
            }
        }
        super.onValueInit();
    }

    protected _updateValue(newValue,oldValue,watchPath){
        
        this.execComponents.forEach(async (comp,index)=>{
            let state = await this.formatValue(newValue,oldValue,comp.node,index,watchPath);
            let _property = this._property;

            comp[_property] = state;
        })
    }

    onCheckProperty(){
        if(this.observerAttr.controlChildren){
            return true;
        }       
        return this._property in this.execComponent;
    }
 }